package org.ucn.dmaa0914.temadesign.group2.tuiLayer;

import java.util.ArrayList;

/**
 * Write a description of class Menu here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Menu extends Display
{
    private ArrayList<String> entries;
    private Menu parentMenu;
    
    private int entryBack;
    
    public Menu(Menu parentMenu, String menuTitle)
    {
        super("Menu: " + menuTitle, "Your Choice: ");
        
        this.parentMenu = parentMenu;
        this.entries = new ArrayList<String>();
        
        if( parentMenu != null )
        {
            setTitle(parentMenu.getTitle() + " -> " + menuTitle);
        }
        else
        {
            setTitle(menuTitle);
        }
        
        if( parentMenu != null )
        {
            entryBack = addEntry("Back");
        }
        else
        {
            entryBack = addEntry("Quit");
        }
    }
    
    /**
     * Rebuilds display content from the current menu entries
     */
    private void buildContentFromEntries()
    {
        // Create menu content
        String content = "Choose an entry: \n";
        
        for( int i = 0; i < entries.size(); ++i  )
        {          
            content += "(" + i + ") " + entries.get(i) + "\n";
        }
        
        setContent(content);
    }
    
    /**
     * Adds a menu entry
     * 
     * @param entry The entry title to add
     */
    public int addEntry(String entry)
    {
        entries.add(entry);
        
        // rebuild content
        buildContentFromEntries();
        
        // Return index of the newly added entry
        return entries.size()-1;
    }
    
    public String execute()
    {
        String result = super.execute();
        
        int entry;
        
        try
        {
            // Try formatting the string into a number
            entry = Integer.parseInt(result);
        }
        catch( NumberFormatException e )
        {
            // Number format error
            entry = -1;
        }
        handleEntry(entry);
        
        return result;
    }
    
    /**
     * Method which is called when an entry has been chosen.
     * 0 means back, -1 means invalid answer
     */
    public void handleEntry(int entryIndex)
    {
        if( entryIndex == entryBack )
        {
            Application.instance.setCurrentMenu(parentMenu);
        }
    }
}
